package com.dz.risk.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dz.risk.common.ResponseVO;
import com.dz.risk.common.exception.RRException;
import com.dz.risk.pojo.domain.TemporaryTableOfDataEntity;
import com.dz.risk.pojo.model.PageModel;
import com.dz.risk.service.TemporaryTableOfDataService;
import com.dz.risk.validation.Add;
import com.dz.risk.validation.Update;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;


/**
 * @author yinpl
 * @email
 * @date 2021-09-02 16:12:01
 */
@Api(tags = "中间表数据api", value = "中间表数据  ")
@RestController
@RequestMapping("dz-ftsp/stest/temporarytableofdata")
public class TemporaryTableOfDataController {
    @Autowired
    private TemporaryTableOfDataService temporaryTableOfDataService;


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ApiOperation("新增临时表数据")
    @PostMapping("/add")
    public ResponseVO add(@RequestBody @Validated(Add.class) TemporaryTableOfDataEntity temporaryTableOfDataEntity) {
        temporaryTableOfDataService.add(temporaryTableOfDataEntity);
        return ResponseVO.ok();
    }

    @ApiOperation("更新临时表数据")
    @PostMapping("/updateById")
    public ResponseVO updateById(@RequestBody @Validated(Update.class) TemporaryTableOfDataEntity temporaryTableOfDataEntity) {
        temporaryTableOfDataService.updateById(temporaryTableOfDataEntity);
        return ResponseVO.ok();
    }

    @ApiOperation("根据Id删除临时表数据")
    @GetMapping("/deleteById")
    public ResponseVO deleteById(@RequestParam("id") String id) {
        temporaryTableOfDataService.removeById(id);
        return ResponseVO.ok();
    }

    /**
     * 查询临时表数据
     */
    @ApiOperation("查询临时表数据")
    @GetMapping(value = "/query")
    public ResponseVO query(PageModel pageModel, TemporaryTableOfDataEntity temporaryTableOfDataEntity) {
        IPage<TemporaryTableOfDataEntity> iPage = null;
        try {
            iPage = temporaryTableOfDataService.query(pageModel, temporaryTableOfDataEntity);

        } catch (RRException e) {
            e.printStackTrace();
            logger.error("查询预警债券名单失败！" + e);
            return new ResponseVO(e.getCode(), e.getMessage());
        }
        return ResponseVO.ok(iPage);

    }


    /**
     * 导入临时表数据
     */
    @ApiOperation("导入临时表数据")
    @PostMapping("/inport")
    public ResponseVO inport(@RequestParam("file") MultipartFile multipartFile, Long version, HttpServletRequest request) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        // params.setTitleRows(0);
        List<TemporaryTableOfDataEntity> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                TemporaryTableOfDataEntity.class, params);
        for (int i = 0; i < result.size(); i++) {
            TemporaryTableOfDataEntity temporaryTableOfDataEntity = result.get(i);
            //temporaryTableOfDataEntity.setDate(version);
            if (temporaryTableOfDataEntity.getIndexId() == null) {
                logger.error("导入参数异常：第" + (i + 1) + "行：编号为空");
                return new ResponseVO(201, "第" + (i + 1) + "行：编号不能为空");
            }
            if (temporaryTableOfDataEntity.getIndexValue() == null) {
                logger.error("导入参数异常：第" + (i + 1) + "行：数据为空");
                return new ResponseVO(201, "第" + (i + 1) + "行：数据不能为空");
            }
            temporaryTableOfDataEntity.setId(StringUtils.remove(UUID.randomUUID().toString(), "-"));

        }
        temporaryTableOfDataService.saveBatch(result);
        return ResponseVO.ok("导入成功");
    }


    /**
     * 导入临时表数据
     */
    @ApiOperation("导出中间表数据模板")
    @GetMapping("/doExportByVersion")
    public void doExportByVersion(HttpServletResponse response) throws IOException {
        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sh = wb.createSheet();
        //indexId	数据	版本号	备注
        String[] titles = {"indexId", "数据", "版本号", "备注"};
        Row row = sh.createRow(0);
        CellStyle style = wb.createCellStyle();
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);

        // 第一行设置标题
        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            Cell cell1 = row.createCell(i);
            cell1.setCellValue(title);
            cell1.setCellStyle(style);
        }

        sh.setColumnWidth(0, 6000);
        sh.setColumnWidth(1, 6000);
        String fileName = "中间表数据.xlsx";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        wb.write(response.getOutputStream());
        wb.close();
    }

    @ApiOperation("编码模板导入")
    @PostMapping("/importOfDataCodingTemplateForDemandForm")
    public ResponseVO importOfDataCodingTemplateForDemandForm(MultipartFile file) throws IOException {
        temporaryTableOfDataService.importOfDataCodingTemplateForDemandForm(file);
        return ResponseVO.ok();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "Date"),
            @ApiImplicitParam(name = "date", value = "数据版本(yyyyMM)", required = true, dataType = "int"),
    })
    @ApiOperation("编码的实际数据导入")
    @PostMapping("/importTheActualDataOfTheTemplateEncoding")
    public ResponseVO importTheActualDataOfTheTemplateEncoding(MultipartFile file, Long date) throws IOException {
        temporaryTableOfDataService.importTheActualDataOfTheTemplateEncoding(file, date);
        return ResponseVO.ok();
    }
}
